package com.lh.buy.manager.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.buy.manager.mapper.TbItemMapper;
import com.lh.buy.manager.mapper.TbItemDescMapper;
import com.lh.buy.util.pojo.EasyUIDatagrideVO;
import com.lh.buy.util.pojo.BuyResult;
import com.lh.pojo.TbItem;
import com.lh.buy.manager.service.ItemService;
import com.lh.pojo.TbItemDesc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Random;

/**
 * @author lh
 * @create 2021-04-16 18:23
 */
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private TbItemMapper tbItemMapper;
    @Autowired
    private TbItemDescMapper tbItemDescMapper;
    @Override
    public TbItem queryById(long itemId) {
        return tbItemMapper.selectById(itemId);
    }

    /**
     *
     * @param page 页面
     * @param rows 显示条数
     * @return  分页查询
     */
    @Override
    public EasyUIDatagrideVO<TbItem> queryByPage(long page, long rows) {
        Page<TbItem> itemPage = new Page<>();
        //设置每页大小
        itemPage.setSize(rows);
        //设置当前页码  内部会自动计算偏移量
        itemPage.setCurrent(page);
        //没有查询条件，所以第二个参数传null
        itemPage=tbItemMapper.selectPage(itemPage,null);
        //准备一个EasyUIDatagrideVO
        EasyUIDatagrideVO<TbItem> datagrideVO = new EasyUIDatagrideVO<>();
        datagrideVO.setTotal(itemPage.getTotal());
        datagrideVO.setRows(itemPage.getRecords());
        return datagrideVO;
    }

    @Override
    //开启事务
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
    public BuyResult save(TbItem tbItem, String desc) {
        //商品的id随机生成  毫秒数+两位随机数
        long itemId=System.currentTimeMillis()+(new Random().nextInt(90)+10);

        tbItem.setId(itemId);
        tbItem.setCreated(new Date());
        tbItem.setUpdated(new Date());
        tbItem.setStatus(1);
        int insert = tbItemMapper.insert(tbItem);
        if(insert==1){
            TbItemDesc tbItemDesc = new TbItemDesc();
            tbItemDesc.setItemId(itemId);
            tbItemDesc.setCreated(new Date());
            tbItemDesc.setUpdated(new Date());
            tbItemDesc.setItemDesc(desc);
            tbItemDescMapper.insert(tbItemDesc);
        }
        return BuyResult.ok();
    }
}
